package com.johnny.springcloud.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class IdGeneratorSnowflake {
    private long workerId = 0; //数据中心 (几号机房)
    private long dataeneterId = 1; //数据中心(几号机器)
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, dataeneterId);

    @PostConstruct //加载一些初始化工作
    public void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()); //得到本地主机的workid编码
            log.info("当前机器的workerId:{}", workerId);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.warn("当前机器的workerId获取失败", ex);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId, long dataeneterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, dataeneterId);
        return snowflake.nextId();
    }

//      public static void main(String[] args){
//          System.out.println(new IdGeneratorSnowflake().snowflakeId());
//       }

}
